package com.hm.health.Activity.ecgflash;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.goodix.RxProgressDialog.RxProgressSubscribe;
import com.goodix.utils.TimeUtil;
import com.goodix.widget.AlertDialogEx;
import com.hm.health.Activity.BaseActivity;
import com.hm.health.R;
import com.hm.health.Utils.TimeUtils;
import com.hm.health.View.EcgHistoryRecordView;
import com.hm.health.records.ecgpatch.EcgPatchRecordReader;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class EcgFlashDetailActivity extends BaseActivity {
    private static final String TAG = "EcgFlashDetailActivity";
    public static final String EXT_ECG_PATCH_TEST_RECORD_ID = "EXT_ECG_PATCH_TEST_RECORD_ID";
    public static final String EXT_ECG_PATCH_CSV_ID = "EXT_ECG_PATCH_CSV_ID";
    public static final String EXT_ECG_PATCH_CSV_TIME = "EXT_ECG_PATCH_CSV_TIME";

    @BindView(R.id.chart_ecg)
    EcgHistoryRecordView mECGChartView;
    @BindView(R.id.tv_starttime)
    TextView mTvStartTime;
    @BindView(R.id.tv_duration)
    TextView mTvDuration;
    @BindView(R.id.tvPathologicalInformation)
    TextView mTvPathologicalInformation;
    @BindView(R.id.tvHrAverage)
    TextView mTvHrAverage;
    @BindView(R.id.ecg_time_text)
    TextView mTvChooseTime;
    @BindView(R.id.ecg_seek_bar)
    SeekBar mSbChooseTime;

    private EcgPatchRecordReader.CurrentHourData mCurrentHourData;

    //String mDayStr;
    //int mHour;
    //private int mRecordNum;
    //private String mFilePath;
    private int mFrequency;
    private int mTestCsvId;
    private long mTestCsvTime;
    private String mTestRecordId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ecg_history_detail);
        ButterKnife.bind(this);
        initActionBar(getString(R.string.ecg_chart_detail));
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mTestRecordId = getIntent().getStringExtra(EXT_ECG_PATCH_TEST_RECORD_ID);
        mTestCsvId = getIntent().getIntExtra(EXT_ECG_PATCH_CSV_ID, 0);
        mTestCsvTime = getIntent().getLongExtra(EXT_ECG_PATCH_CSV_TIME, 0l);
        mTvPathologicalInformation.setText(R.string.ecg_test_records);

        initView();
    }

    private void initView() {
        Observable.create((Observable.OnSubscribe<String>) subscriber -> {
            mCurrentHourData = EcgPatchRecordReader.getInstance().loadDataList(mTestRecordId, mTestCsvId, mTestCsvTime);

            // insert data to mDatas by currentHourData.mTimestamps and mLeadState
            mCurrentHourData.insertBlankByLead();

            subscriber.onCompleted();
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxProgressSubscribe<>(getString(R.string.ecg_flash_data_loading),
                        new Observer<String>() {
                            @Override
                            public void onCompleted() {
                                if (mCurrentHourData == null) {
                                    AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
                                    builder.setMessage(getString(R.string.failed_get_test_records));
                                    builder.setNegativeButton(R.string.quit, view -> finish());
                                    builder.show();
                                }
                                mTvStartTime.setText(TimeUtil.formateTime(mCurrentHourData.mStartTimestamp));
                                mTvDuration.setText(String.format(getString(R.string.ecg_duration_format),
                                        TimeUtils.timeDifference(mCurrentHourData.mStartTimestamp, mCurrentHourData.mEndTimestamp)));
                                mTvHrAverage.setText(String.format("%d BPM", mCurrentHourData.mHrv));

                                int frequency = (mCurrentHourData.mFrequency > 0) ? mCurrentHourData.mFrequency : 500;
                                mFrequency = frequency;
                                initData(frequency);

                                if (mCurrentHourData.mEndTimestamp - mCurrentHourData.mStartTimestamp < 2 * 1000) {
                                    mSbChooseTime.setEnabled(false);
                                }

                                mSbChooseTime.setMax(mCurrentHourData.mDatas.size());
                                mTvChooseTime.setText(TimeUtil.formateEcgSecond(mCurrentHourData.mStartTimestamp));
                                mSbChooseTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                    @Override
                                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                        String chooseTime = TimeUtil.formateEcgSecond(
                                                mCurrentHourData.mStartTimestamp + 1000 / frequency * progress);
                                        Log.d(TAG, "choose progress=" + progress + ", time=" + chooseTime);
                                        runOnUiThread(() -> {
                                            mECGChartView.refreshByChooseTime(progress);
                                            mTvChooseTime.setText(chooseTime);
                                        });
                                    }

                                    @Override
                                    public void onStartTrackingTouch(SeekBar seekBar) {

                                    }

                                    @Override
                                    public void onStopTrackingTouch(SeekBar seekBar) {

                                    }
                                });
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String data) {
                            }
                        }, mContext));

        mECGChartView.setEcgDataLister(progress -> runOnUiThread(() -> {
            int value = progress;
            if (value < 0) {
                value = 0;
            }
            if (value > mSbChooseTime.getMax()) {
                value = mSbChooseTime.getMax();
            }
            mSbChooseTime.setProgress(value);
            mTvChooseTime.setText(TimeUtil.formateEcgSecond(mCurrentHourData.mStartTimestamp + 1000 / mFrequency * value));
        }));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_export:
                onExportBtnClicked(item.getActionView());
                break;
            case R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onExportBtnClicked(View actionView) {
        /// Todo
        Intent intent = new Intent(mContext, EcgFlashExportToPdfActivity.class);
        intent.putExtra(EXT_ECG_PATCH_TEST_RECORD_ID, mTestRecordId);
        intent.putExtra(EXT_ECG_PATCH_CSV_ID, mTestCsvId);
        intent.putExtra(EXT_ECG_PATCH_CSV_TIME, mTestCsvTime);

        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ecg_detail_info, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void initData(int frequency) {
        mECGChartView.setDatas(mCurrentHourData.mDatas, mCurrentHourData.mLeadState);
        refreshPlot(frequency);
    }

    private void refreshPlot(int frequency) {
        mECGChartView.setFrequency(frequency);
        mECGChartView.setEnableDrag(true);
        mECGChartView.setYAxisMaxValue(2f);
        mECGChartView.setYAxisMinValue(-1.5f);
        mECGChartView.invalidate();
    }
}
